/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* left;
    Node* right;

    Node() {}

    Node(int _val) {
        val = _val;
        left = NULL;
        right = NULL;
    }

    Node(int _val, Node* _left, Node* _right) {
        val = _val;
        left = _left;
        right = _right;
    }
};
*/
class Solution {
public:
    void test(Node* cur,Node*& prev)//prev一定是引用
    {
        //中序
        if(cur==nullptr)
        {
            return;
        }
        //先往左走
        test(cur->left,prev);

        cur->left=prev;
        if(prev) prev->right=cur;
        prev=cur;      

        test(cur->right,prev);                
    }
    Node* treeToDoublyList(Node* root) {
        if(root==nullptr) return root;
        //中序的时候调整，调整完之后弄成循环链表
        Node* prev=nullptr;
        test(root,prev);

        Node* head=root;
        while(head->left)
        {
            head=head->left;
        }
        head->left=prev;
        prev->right=head;

        return head;
    }
};